package ifgi.potwc.ipt.upload;

import ifgi.potwc.ipt.R;
import ifgi.potwc.ipt.store.Store;
import ifgi.potwc.ipt.ui.SettingsActivity;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * This class schedules all data uploads to Cosm.
 * 
 * @author saschak.
 */
public class IptUploadService extends Service
{
    // Context
    private Context ctx;

    // SharedPreferences
    private SharedPreferences prefs;

    // Upload Manager
    private IptUploadManager uploadManager;

    // Timer and TimerTask
    private Timer timer;
    private UploadTimerTask uploadTimerTask;

    @Override
    public void onCreate()
    {
	super.onCreate();

	// Initialize attributes
	ctx = getApplicationContext();
	prefs = SettingsActivity.getPrefs((ContextWrapper) ctx);
	uploadManager = new IptUploadManager(ctx);
	timer = new Timer();
	uploadTimerTask = new UploadTimerTask();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
	// Log.d("IptUploadService", "UploadService started");

	long uploadFreq = Long.parseLong(prefs.getString("pref_upload_freq",
		"1")) * Store.HOURS;

	// Start the Upload Timer Task
	timer.scheduleAtFixedRate(uploadTimerTask, uploadFreq, uploadFreq);

	// If the system kills the service, it will be recreated and called with
	// the last intent that was delivered to it.
	return Service.START_STICKY;
    }

    @Override
    public void onDestroy()
    {
	// Cancel timertask
	uploadTimerTask.cancel();

	// Upload all database entries that have not been uploaded yet
	uploadManager.uploadDatabase();

	// Log.d("IptUploadService", "TimerTask cancelled");

	// Inform the user that the Upload service has been stopped.
	Toast.makeText(ctx, R.string.uploadServiceStopped, Toast.LENGTH_SHORT)
		.show();

	super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0)
    {
	// Binding is not used, so return null
	return null;
    }

    // ***************************************************************************
    // Upload Timer Task

    /**
     * Handles all processes that should repeat at upload frequency.
     * 
     * @author saschak.
     */
    class UploadTimerTask extends TimerTask
    {
	@Override
	public void run()
	{
	    // Current feed ID from SharedPreferences
	    String currentFeedID = prefs.getString(Store.FEED_ID, "");

	    Log.d("currentFeedID", currentFeedID);

	    // Upload database
	    uploadManager.uploadDatabase();
	}
    }
}